#include <stdio.h>
#include <pthread.h>

#define THREAD_COUNT 2

int shared_data = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void* thread_func(void* arg) {
    int thread_id = *(int*)arg;

    // 线程对共享数据进行更改
    pthread_mutex_lock(&mutex);
    shared_data++;
    printf("Thread %d: shared_data = %d\n", thread_id, shared_data);
    pthread_mutex_unlock(&mutex);

    return NULL;
}

int main() {
    pthread_t threads[THREAD_COUNT];
    int thread_ids[THREAD_COUNT];

    // 创建多个线程
    for (int i = 0; i < THREAD_COUNT; i++) {
        thread_ids[i] = i + 1;
        pthread_create(&threads[i], NULL, thread_func, &thread_ids[i]);
    }

    // 等待所有线程完成
    for (int i = 0; i < THREAD_COUNT; i++) {
        pthread_join(threads[i], NULL);
    }

    // 输出共享数据
    printf("Main thread: shared_data = %d\n", shared_data);

    return 0;
}
